import type { UploadProgressEvent } from 'element-plus'
import axiosInstance from '@/utils/request'

//重试异常
class RetryError extends Error {}

//失败异常
class FatalError extends Error {}

export const fileApi = {
  uploadFile: async (file: File, progress?: (evt: UploadProgressEvent) => void) => {
    const formData = new FormData()
    formData.append('file', file)
    // proxyAxios.sseRequest({
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'multipart/form-data'
    //   },
    //   data: formData,
    //   url: '/api/admin/file/upload',
    //   sseCallback: (event,str) => {
    //     // console.log(str)
    //     // console.log(event)
    //   }
    // })
    // if (formData) {
    //   return
    // }
    axiosInstance
      .request({
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        data: formData,
        url: '/api/admin/file/upload',
        responseType: 'stream',
        adapter: 'fetch' //fetch适配器
      })
      .then(async (res) => {
        // const data= res.data
        // console.log(res.data)

        const stream: ReadableStream = res.data
        const reader = stream.getReader()

        let buffer = ''
        const decoder = new TextDecoder()
        try {
          while (true) {
            const { value, done } = await reader.read()
            if (done) {
              break
            }

            // 将 ArrayBuffer 转换为字符串
            const chunk = decoder.decode(value, { stream: true })

            // 处理 SSE 数据
            buffer += chunk

            // 当遇到完整的 SSE 事件时进行处理
            while (buffer.indexOf('\n\n') !== -1) {
              const eventEnd = buffer.indexOf('\n\n')
              //一个完整的事件，可能包含event和多个data
              const event = buffer.slice(0, eventEnd)
              buffer = buffer.slice(eventEnd + 2)
              // 解析事件
              const messages = event.split('\n')
              // 找到以 "event:" 开头的行
              const eventNameLine = messages.find((line) => line.startsWith('event:'))
              //事件名
              const eventName = eventNameLine ? eventNameLine.substring(6) : ''

              const idLine = messages.find((line) => line.startsWith('id:'))
              const id = idLine ? idLine.substring(3) : ''

              const commentLine = messages.find((line) => line.startsWith(':'))
              const comment = commentLine ? commentLine.substring(1) : ''

              const retryLine = messages.find((line) => line.startsWith('retry:'))
              const retry = retryLine ? retryLine.substring(6) : ''

              // 获取事件的内容
              const dataLines = messages.filter((line) => line.startsWith('data:'))
              //事件内容，合并多个data后保留换行符
              const data = dataLines.map((line) => line.substring(5)).join('\n')
              console.log({
                id,
                retry,
                comment,
                event: eventName,
                data
              })
            }
          }
        } finally {
          reader.releaseLock()
        }
      })

    // const ctrl = new AbortController()
    // const formData = new FormData()
    // formData.append('file', file)
    // const sse = fetchEventSource('/dev-api/api/admin/file/upload', {
    //   method: 'POST',
    //   headers: {
    //     'USER-ID': `1`,
    //     'PLATFORM': 'ADMIN'
    //   },
    //   body: formData,
    //   signal: ctrl.signal,
    //   // onopen: async (response) => {
    //   //   console.log("open",response)
    //   // },
    //   onmessage: (response) => {
    //     const result = response.data
    //     const { data } = JsonUtils.parse(result)
    //     let percent = Math.round(data.progress * 100)
    //     progress?.({
    //       percent,
    //       ...({} as any)
    //     })
    //   }
    // })

    // fetchEventSource('/dev-api/api/admin/file/upload', {
    //   async onopen(response) {
    //     if (response.ok && response.headers.get('content-type') === EventStreamContentType) {
    //       return; // everything's good
    //     } else if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    //       // client-side errors are usually non-retriable:
    //       throw new FatalError();
    //     } else {
    //       throw new RetryError();
    //     }
    //   },
    //   onmessage(msg) {
    //     // if the server emits an error message, throw an exception
    //     // so it gets handled by the onerror callback below:
    //     if (msg.event === 'FatalError') {
    //       throw new FatalError(msg.data);
    //     }
    //   },
    //   onclose() {
    //     // if the server closes the connection unexpectedly, retry:
    //     throw new RetryError();
    //   },
    //   onerror(err) {
    //     if (err instanceof FatalError) {
    //       throw err; // rethrow to stop the operation
    //     } else {
    //       // do nothing to automatically retry. You can also
    //       // return a specific retry interval here.
    //     }
    //   }
    // });

    // return service.upload<any>('/admin/file/uploadFile', uploadFileDto, {
    //   onUploadProgress: (progressEvent: AxiosProgressEvent) => {
    //     console.log(progressEvent)
    //     let percent = Math.round((progressEvent.loaded * 100) / progressEvent.total!)
    //     if (progress) {
    //       progress({
    //         percent: percent,
    //         ...progressEvent.event
    //       });
    //     }
    //   },
    // });
  }
}
